package comHttp

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"time"
)

// HTTPClient 封装结构体
type HTTPClient struct {
	BaseURL     string
	BASICToken  string
	BearerToken string
	Timeout     time.Duration
}

// NewHTTPClient 创建新的 HTTPClient
func NewHTTPClient(baseURL, bearerToken string, BASICToken string, timeout time.Duration) *HTTPClient {
	return &HTTPClient{
		BaseURL:     baseURL,
		BearerToken: bearerToken,
		BASICToken:  BASICToken,
		Timeout:     timeout,
	}
}

// Request 通用 HTTP 请求方法
func (c *HTTPClient) Request(method, endpoint string, body interface{}) ([]byte, int, error) {
	client := &http.Client{Timeout: c.Timeout}

	// 构造 URL
	url := fmt.Sprintf("%s%s", c.BaseURL, endpoint)

	// 处理 Body
	var requestBody []byte
	var err error
	if body != nil {
		requestBody, err = json.Marshal(body)
		if err != nil {
			return nil, 0, fmt.Errorf("序列化请求体失败: %v", err)
		}
	}

	// 创建请求
	req, err := http.NewRequest(method, url, bytes.NewBuffer(requestBody))
	if err != nil {
		return nil, 0, fmt.Errorf("创建请求失败: %v", err)
	}

	// 设置 Headers
	req.Header.Set("Content-Type", "application/json")
	if c.BearerToken != "" {
		req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.BearerToken))
	}
	if c.BASICToken != "" {
		req.Header.Set("Authorization", fmt.Sprintf("BASIC %s", c.BASICToken))
	}
	// 执行请求
	resp, err := client.Do(req)
	if err != nil {
		return nil, 0, fmt.Errorf("请求失败: %v", err)
	}
	defer resp.Body.Close()

	// 读取响应
	responseBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, 0, fmt.Errorf("读取响应失败: %v", err)
	}

	return responseBody, resp.StatusCode, nil
}

// Get  请求
func (c *HTTPClient) Get(endpoint string) ([]byte, int, error) {
	return c.Request(http.MethodGet, endpoint, nil)
}

// Post  请求
func (c *HTTPClient) Post(endpoint string, body interface{}) ([]byte, int, error) {
	return c.Request(http.MethodPost, endpoint, body)
}

// Put  请求
func (c *HTTPClient) Put(endpoint string, body interface{}) ([]byte, int, error) {
	return c.Request(http.MethodPut, endpoint, body)
}

// Delete 请求
func (c *HTTPClient) Delete(endpoint string, body interface{}) ([]byte, int, error) {
	return c.Request(http.MethodDelete, endpoint, body)
}

//// 示例使用
//func main() {
//	client := NewHTTPClient("http://example.com", "your_jwt_token", 10*time.Second)
//
//	// 示例 GET 请求
//	resp, statusCode, err := client.Get("/api/resource")
//	if err != nil {
//		fmt.Printf("GET 请求失败: %v\n", err)
//	} else {
//		fmt.Printf("GET 请求成功: 状态码 %d, 响应 %s\n", statusCode, resp)
//	}
//
//	// 示例 POST 请求
//	data := map[string]interface{}{
//		"key": "value",
//	}
//	resp, statusCode, err = client.Post("/api/resource", data)
//	if err != nil {
//		fmt.Printf("POST 请求失败: %v\n", err)
//	} else {
//		fmt.Printf("POST 请求成功: 状态码 %d, 响应 %s\n", statusCode, resp)
//	}
//}
